In [56]:
list1 = [["a", "b", "c"], [1, 2, 3]]
# print tuple(["a", "b", "c"])
# print tuple([1, 2, 3])
map(tuple, list1)
for item in list1:
tuple(item)
In [61]:
table1 = [["a", "b", "c"], [1, 2, 3]]
table2 = [["a", "b", "c"], [1, 2, 3]]
table3 = [["a", "b", "c"], [1, 2, 4]]
table4 = [[1, 2, 3], ["a", "b", "c"]]
# list.sort()
# sorted(list)
def is_equal(t1, t2):
t1.sort()
t2.sort()
return t1 == t2
In [ ]:
# Create a set
one_set = set()
In [58]:
# Constructor takes a single argument that is an iterable
another_set = set('aaabcc')
print(another_set)
In [ ]:
A module is a file that contain Python code. Large programs are easier to debug and maintain when they are divided into modules.
We have already been using this feature. Each exercise is a module. Test modules import program modules
Suppose you have been asked to write a program that calculates the following.
What modules would you create? What functions would you create?
def function_name():
statement
statement
statement
Functions are either a void function or a value-returning function.
In [ ]:
# Turn this code into a function
def what_to_wear(temperature):
output = ""
if (temperature < 15):
output = "Wear a coat."
return output
what_to_wear(8)
When we design a program, we have to plan ahead to use functions effectively. Taking a problem or program and breaking it into sub-parts is calle top-down design.
In [63]:
def get_hourly_rate():
print ("get_hourly_rate")
def get_hours_worked():
print ("get_hours_worked")
def get_input():
print ("get_input")
get_hours_worked()
get_hourly_rate()
def main():
print("main")
get_input()
main()
Your alarm clock as a software object. It would have the following data attributes.
These attributes define the state of the alarm clock.
These attributes are private, meaning you can't change them.
But you can use public methods (buttons) to change them.
There are private methods that are part of the clock's internal workings.
In [65]:
import random
# The Coin class simulates a coin that can be flipped
class Coin:
# The __init__ methods is the constructor
def __init__(self):
self.sideup = 'Heads'
def toss(self):
flip = random.randint(0, 1)
if flip == 0:
self.sideup = "Heads"
else:
self.sideup = "Tails"
def get_sideup(self):
return self.sideup
In [66]:
def main():
my_coin = Coin()
print("This side is up: " + my_coin.get_sideup())
print("I am tossing the coin...")
my_coin.toss()
print("This side is up: " + my_coin.get_sideup())
In [70]:
main()
In [72]:
for _ in range(5):
print random.randint(0, 1)
To start using a file, given its filename, you have to open it. But first, the name— a string. How we get that string depends on our needs. Here are a few options.
Once we have the filename, we need to turn it into something that the Python program can work with. This involves creating a file handle or file object, by opening the file.
In [73]:
with open("jabberwocky.txt", "r") as file_reader:
# insert file operation here
file_contents = file_reader.read()
print file_contents
When opening a file, there are some things that can go wrong. The file might not exist. The program might not have permission to access the file. There might be a hardware error that occurs during access. For these reasons, file reading usually occurs after some checking or within a try-except block.
Once we are done accessing the file, we have to close it. The contents aren’t actually saved to disk until we close it. Closing the file also reduces the resources used by our program and makes the file available for others to access.
If we didn't have "with", here's what the code would look like.
In [46]:
file_name = "jabberwocky.txt"
try:
file_reader = open(file_name)
# file read operation goes here
except(OSError, IOError):
print("Error reading file: " + file_name)
else:
s = file_reader.read()
file_reader.close()
In [75]:
file_name = "jabberwocky.txt"
In [47]:
# All at once into a string
with open(file_name) as file_reader:
file_contents = file_reader.read()
In [ ]:
# All at once into a list
with open(file_name) as file_reader:
file_contents = file_reader.readlines()
In [ ]:
# All lines, one at a time
with open(file_name) as file_reader:
for line in file_reader:
print (line),
In [81]:
# One line at a time
with open(file_name) as file_reader:
line = file_reader.readline()
print(line)
line= file_reader.readline()
print(line)
line = file_reader.readline()
print(line)
In [ ]:
# By groups of characters
with open(file_name) as file_reader:
input_group = file_reader.read(10) # Read 10 characters
print(input_group)
input_group = file_reader.read(10) # Read the next 10 characters
print(input_group)
Unless you choose to stop reading, you will eventually reach the end of an input file, called “EOF”. The the first three approaches automatically recognizes EOF. With the remaining two, you have to detect the situation of being at EOF yourself.
If you are at EOF, when you call read() or readline() you get an empty string.
Note: An empty string is not the same as a blank line.
In [ ]:
# Open a file called filename and read line by line until EOF is reached
In [82]:
file_name = "missive.txt"
with open(file_name, 'w') as output_file:
output_file.write("Dear Uncle Marty,\n")
output_file.write("Thanks for the nifty present.\n")
output_file.write("Love,\nYour Niece\n")
In [83]:
output_file = open(file_name, 'w')
output_file.write("Dear Uncle Marty,\n")
output_file.write("Thanks for the nifty present.\n")
output_file.write("Love,\nYour Niece\n")
kb_hit = raw_input("waiting...")
output_file.close()
In [ ]: